//
//  Hear_PhonographView.m
//  Hear
//
//  Created by mac on 2018/4/26.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_PhonographView.h"

#import "EmitterBtn.h"

#import "HRUMShareTool.h"

@interface Hear_PhonographView() <UIGestureRecognizerDelegate>

/** 点赞按钮 */
@property (nonatomic, strong) EmitterBtn *favoriteBtn;

@end

@implementation Hear_PhonographView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    // 背景
    SDCycleScrollView *scrollview = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:self placeholderImage:GetImgWithStr(@"Phonograph_bg")];
    scrollview.autoScrollTimeInterval = 3.0;
    scrollview.showPageControl = NO;
    scrollview.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    self.scrollview = scrollview;
    [self addSubview:scrollview];
    
    UIImageView *coverimage = [[UIImageView alloc] initWithImage:GetImgWithStr(@"背景蒙版")];
    coverimage.userInteractionEnabled = YES;
    [scrollview addSubview:coverimage];
    
    [scrollview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self);
    }];
    [coverimage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    tap.delegate = self;
    [coverimage addGestureRecognizer:tap];
    
    UILongPressGestureRecognizer *longGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGesAction:)];
    longGes.minimumPressDuration = 1.0;
    longGes.delegate = self;
    [coverimage addGestureRecognizer:longGes];
    
    [tap requireGestureRecognizerToFail:longGes];
    
    // 话题
    UIView *showview = [UIView new];
    showview.layer.cornerRadius = 10;
    showview.layer.masksToBounds = YES;
    showview.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2];
    [coverimage addSubview:showview];
    
    [showview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(coverimage.mas_leading).mas_offset(20 * scaleWidth);
        make.trailing.mas_equalTo(coverimage.mas_trailing).mas_offset(-20 * scaleWidth);
        make.top.mas_equalTo(coverimage.mas_top).mas_offset(22 * scaleHeight);
        make.height.mas_equalTo(100 * scaleHeight);
    }];
    
    UILabel *titleLB = [UILabel new];
    titleLB.font = [UIFont systemFontOfSize:15];
    titleLB.textColor = [UIColor colorWithHexString:@"#ffffff"];
    titleLB.textAlignment = NSTextAlignmentCenter;
    titleLB.numberOfLines = 0;
    titleLB.userInteractionEnabled = YES;
    self.titleLB = titleLB;
    [showview addSubview:titleLB];
    
    UITapGestureRecognizer *titleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleTapAction:)];
    [titleLB addGestureRecognizer:titleTap];
    
    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(showview);
        make.leading.mas_equalTo(showview.mas_leading).mas_offset(17 * scaleWidth);
        make.trailing.mas_equalTo(showview.mas_trailing).mas_offset(-17 * scaleWidth);
        make.top.mas_equalTo(showview.mas_top).mas_offset(19 * scaleHeight);
        make.height.mas_equalTo(39 * scaleHeight);
    }];
    
//    UIButton *sharebtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [sharebtn setImage:GetImgWithStr(@"话题转发") forState:UIControlStateNormal];
//    [sharebtn addTarget:self action:@selector(sharebtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    [showview addSubview:sharebtn];
//
//    [sharebtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.trailing.mas_equalTo(titleLB.mas_trailing);
//        make.bottom.mas_equalTo(showview.mas_bottom).mas_offset(-12 * scaleHeight);
//        make.size.mas_equalTo(CGSizeMake(17 * scaleWidth, 17 * scaleHeight));
//    }];
    
    UIButton *answerbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [answerbtn setImage:GetImgWithStr(@"答") forState:UIControlStateNormal];
    [answerbtn addTarget:self action:@selector(answerbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [coverimage addSubview:answerbtn];
    [coverimage bringSubviewToFront:answerbtn];
    
    [answerbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(coverimage.mas_top).mas_offset(99 * scaleHeight);
        make.centerX.mas_equalTo(coverimage);
        make.size.mas_equalTo(CGSizeMake(45 * scaleWidth, 45 * scaleHeight));
    }];
    
    // 播放按钮
    UIButton *playbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playbtn setImage:GetImgWithStr(@"暂停") forState:UIControlStateNormal];
    [playbtn addTarget:self action:@selector(playbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.playbtn = playbtn;
    self.playbtn.hidden = YES;
    [self addSubview:playbtn];
    
    [playbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(self);
        make.size.mas_equalTo(CGSizeMake(70 * scaleWidth, 70 * scaleHeight));
    }];
    
    // 题主
    UIImageView *header = [[UIImageView alloc] init];
    header.layer.cornerRadius = 17;
    header.layer.masksToBounds = YES;
    header.userInteractionEnabled = YES;
    self.header = header;
    [coverimage addSubview:header];
    
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(answerbtn.mas_bottom).mas_offset(35 * scaleHeight);
        make.trailing.mas_equalTo(coverimage.mas_trailing).mas_offset(-27 * scaleWidth);
        make.size.mas_equalTo(CGSizeMake(34, 34));
    }];
    
    UILabel *name = [UILabel new];
    name.backgroundColor = [UIColor colorWithHexString:@"#FEB73D"];
    name.textColor = [UIColor whiteColor];
    name.font = [UIFont systemFontOfSize:12];
    name.textAlignment = NSTextAlignmentCenter;
    name.text = @"题主";
    name.layer.cornerRadius = 5;
    name.layer.masksToBounds = YES;
    [coverimage addSubview:name];
    
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(header.mas_bottom).mas_offset(-1 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(34 * scaleWidth, 14 * scaleHeight));
    }];
    
    UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerTapAction)];
    [header addGestureRecognizer:headerTap];
    
    // 点赞
    EmitterBtn *favoriteBtn = [EmitterBtn buttonWithType:UIButtonTypeCustom];
    [favoriteBtn setImage:GetImgWithStr(@"未点赞") forState:UIControlStateNormal];
    [favoriteBtn setImage:GetImgWithStr(@"已点赞") forState:UIControlStateSelected];
    [favoriteBtn setImage:GetImgWithStr(@"已点赞") forState:UIControlStateHighlighted];
    [favoriteBtn addTarget:self action:@selector(favoritebtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.favoriteBtn = favoriteBtn;
    [coverimage addSubview:favoriteBtn];
    
    [favoriteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(name.mas_bottom).mas_offset(29 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(27.5 * scaleWidth, 24.5 * scaleHeight));
    }];
    
    UILabel *favorite = [UILabel new];
    favorite.textColor = [UIColor whiteColor];
    favorite.font = [UIFont systemFontOfSize:13];
    favorite.textAlignment = NSTextAlignmentCenter;
    favorite.text = @"0";
    self.favorite = favorite;
    [coverimage addSubview:favorite];
    
    [favorite mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(favoriteBtn.mas_bottom).mas_offset(12 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(27.5 * scaleWidth, 14 * scaleHeight));
    }];
    
    // 评论
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [commentBtn setImage:GetImgWithStr(@"Phonograph_评论") forState:UIControlStateNormal];
    [commentBtn addTarget:self action:@selector(commentBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [coverimage addSubview:commentBtn];
    
    [commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(favorite.mas_bottom).mas_offset(29 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(27.5 * scaleWidth, 27.5 * scaleHeight));
    }];
    
    UILabel *comment = [UILabel new];
    comment.textColor = [UIColor whiteColor];
    comment.font = [UIFont systemFontOfSize:13];
    comment.textAlignment = NSTextAlignmentCenter;
    comment.text = @"0";
    self.comment = comment;
    [coverimage addSubview:comment];
    
    [comment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(commentBtn.mas_bottom).mas_offset(12 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(27.5 * scaleWidth, 14 * scaleHeight));
    }];
    
    // 转发
    UIButton *forwardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [forwardBtn setImage:GetImgWithStr(@"Phonograph_转发") forState:UIControlStateNormal];
    [forwardBtn addTarget:self action:@selector(forwardBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [coverimage addSubview:forwardBtn];
    
    [forwardBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(comment.mas_bottom).mas_offset(29 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(26.5 * scaleWidth, 24.5 * scaleHeight));
    }];
    
    UILabel *forward = [UILabel new];
    forward.textColor = [UIColor whiteColor];
    forward.font = [UIFont systemFontOfSize:13];
    forward.textAlignment = NSTextAlignmentCenter;
    forward.text = @"0";
    self.forward = forward;
    [coverimage addSubview:forward];
    
    [forward mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(forwardBtn.mas_bottom).mas_offset(12 * scaleHeight);
        make.centerX.mas_equalTo(header);
        make.size.mas_equalTo(CGSizeMake(27.5 * scaleWidth, 14 * scaleHeight));
    }];
    
    // 转动头像
    UIImageView *rotatingImg = [[UIImageView alloc] initWithImage:GetImgWithStr(@"")];
    rotatingImg.layer.cornerRadius = 22.5;
    rotatingImg.layer.masksToBounds = YES;
    rotatingImg.userInteractionEnabled = YES;
    self.rotatingImg = rotatingImg;
    [coverimage addSubview:rotatingImg];
    
    [rotatingImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(coverimage.mas_leading).mas_offset(25 * scaleWidth);
        make.bottom.mas_equalTo(coverimage.mas_bottom).mas_offset(-30 * scaleHeight);
        make.size.mas_equalTo(CGSizeMake(45, 45));
    }];
    
    UITapGestureRecognizer *rotateTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rotatingImgTap)];
    [rotatingImg addGestureRecognizer:rotateTap];
    
    // 题主名称
    UILabel *owner = [UILabel new];
    owner.textColor = [UIColor whiteColor];
    owner.font = [UIFont systemFontOfSize:16];
    owner.textAlignment = NSTextAlignmentLeft;
    owner.text = @"昵称显示";
    self.owner = owner;
    [coverimage addSubview:owner];
    
    [owner mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(rotatingImg.mas_trailing).mas_offset(17.5 * scaleWidth);
        make.top.mas_equalTo(rotatingImg.mas_top);
    }];
    
    // 题主性别
    UIImageView *seximg = [[UIImageView alloc] initWithImage:GetImgWithStr(@"")];
    self.seximg = seximg;
    [coverimage addSubview:seximg];
    
    [seximg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(owner.mas_leading);
        make.top.mas_equalTo(owner.mas_bottom).mas_offset(10 * scaleHeight);
        make.size.mas_equalTo(CGSizeMake(14 * scaleWidth, 14 * scaleHeight));
    }];
    
    // 题主年龄
    UILabel *year = [UILabel new];
    year.textColor = [UIColor whiteColor];
    year.font = [UIFont systemFontOfSize:12];
    year.textAlignment = NSTextAlignmentLeft;
    self.year = year;
    [coverimage addSubview:year];
    
    [year mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(seximg.mas_trailing).mas_offset(8.5 * scaleWidth);
        make.centerY.mas_equalTo(seximg);
    }];
}

#pragma mark 标题点击事件
- (void)titleTapAction:(UITapGestureRecognizer *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographTitleTapAction" object:self.model];
}

#pragma mark 分享
//- (void)sharebtnAction:(UIButton *)sender {
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographShare" object:self.model];
//}

#pragma mark 回答
- (void)answerbtnAction:(UIButton *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographAnswer" object:self.model];
}

#pragma mark  播放事件
- (void)playbtnAction:(UIButton *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographPlay" object:sender];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographRotatingImg" object:self.rotatingImg];
}

#pragma mark  界面点击事件
- (void)tapAction {
    self.playbtn.hidden = !self.playbtn.hidden;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographPlay" object:self.playbtn];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographRotatingImg" object:self.rotatingImg];
}

- (void)longGesAction:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographlongGes" object:self.model];
    }
}

#pragma mark 点击头像事件
- (void)headerTapAction {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographHeaderTap" object:self.model];
}

#pragma mark 点赞事件
- (void)favoritebtnAction {
    if ([self.enble isEqualToString:@"1"]) {
        return;
    }
    if (self.favoriteBtn.selected) return;
    
    self.favoriteBtn.selected = !self.favoriteBtn.isSelected;
    [self.favoriteBtn starAmimation];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"MomentLocalId"] = self.model.MomentLocalId;
    param[@"LocalId"] = self.model.LocalId;
    param[@"UserLocalId"] = USERID;
    param[@"CreateTime"] = [self getCurrentTime];
    
    YTKApi *api = [YTKApi apiPostWithUrl:@"MomentsInfo/Post_SaveMomentsLike" para:param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            if ([dict[@"CodeStatus"] intValue] == 20000){
                self.model.IsDoLike = @"1";
                self.favoriteBtn.selected = YES;
                self.favorite.text = [NSString stringWithFormat:@"%d",[self.favorite.text intValue] + 1 ];
                
                self.model.LikeCount = [NSString stringWithFormat:@"%d",[self.model.LikeCount intValue] + 1 ];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographFavorite" object:self.model];
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
    
}

#pragma mark 评论
- (void)commentBtnAction:(UIButton *)sender {
    if ([self.enble isEqualToString:@"1"]) {
        return;
    }
    
    self.comment.text = [NSString stringWithFormat:@"%d",[self.comment.text intValue] + 1 ];
    
    self.model.CommentCount = [NSString stringWithFormat:@"%d",[self.model.CommentCount intValue] + 1 ];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographComment" object:self.model];
}

#pragma mark 转发
- (void)forwardBtnAction:(UIButton *)sender {
    
    if ([self.enble isEqualToString:@"1"]) {
        return;
    }
    
    NSString *title = @"";
    if (self.model.QuestionText.length){
        title = self.model.QuestionText;
    } else {
        title = @"我在Hear留下的瞬间";
    }
    
    if (self.model.BackGround) {
        NSData *jsondata = [self.model.BackGround dataUsingEncoding:NSUTF8StringEncoding];
        
        NSArray *imageArr = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        NSString *image = imageArr[0];
        
        NSString *images =  [image stringByReplacingOccurrencesOfString:@"http" withString:@"https"];
        
        [HRUMShareTool uMShareToolTitle:title andContentStr:@"又是平常又唯一的一天，我有个秘密要告诉你。" thumImage:images andShareUrl:[NSString stringWithFormat:@"http://www.dolphinvoice.com/M/VoiceShare/%@", self.model.LocalId] isSeccess:^(BOOL isSeccess) {
            self.forward.text = [NSString stringWithFormat:@"%d",[self.forward.text intValue] + 1 ];
            [self showMessage:@"分享成功" atPosition:ShowPosition_Bottom];
            // 转发成功后进行转发记录
            [self saveRecordWithModel:self.model];
        }];
        
    } else {
        
        [HRUMShareTool uMShareToolTitle:title andContentStr:@"又是平常又唯一的一天，我有个秘密要告诉你。" andImage:[UIImage imageNamed:@"hearicon"] andShareUrl:[NSString stringWithFormat:@"http://www.dolphinvoice.com/M/VoiceShare/%@", self.model.LocalId] isSeccess:^(BOOL isSeccess) {
            
            self.forward.text = [NSString stringWithFormat:@"%d",[self.forward.text intValue] + 1 ];
            [self showMessage:@"分享成功" atPosition:ShowPosition_Bottom];
            // 转发成功后进行转发记录
            [self saveRecordWithModel:self.model];
        }];
        
    }
    
    
}

#pragma mark 转发成功调用记录接口
- (void)saveRecordWithModel:(Hear_PhonographRecommendModel *)model {
    NSDictionary *param = @{
                            @"SoundLocalId":self.model.LocalId,
                            @"ShareType":@"1",
                            @"UserLocalId":USERID,
                            @"CreateTime":[self getCurrentTime]
                            };
    
    YTKApi *api = [YTKApi apiPostWithUrl:@"SoundInfo/Post_SaveSoundShareRecord" para:param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            if ([dict[@"CodeStatus"] intValue] == 20000){
                
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}

#pragma mark 题主头像点击事件
- (void)rotatingImgTap {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_PhonographRotatingTap" object:self.model];
}

#pragma mark 界面赋值
- (void)setModel:(Hear_PhonographRecommendModel *)model {
    
    _model = model;
    
    // 背景图
    if (model.BackGround) {
        NSData *jsondata = [model.BackGround dataUsingEncoding:NSUTF8StringEncoding];
        
        NSArray *imageArr = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        if (imageArr.count == 1) {
            self.scrollview.autoScroll = NO;
        } else {
            self.scrollview.autoScroll = YES;
        }
        
        self.scrollview.imageURLStringsGroup = imageArr;
        
    }
    
    // 话题
    self.titleLB.text = model.QuestionText;
    
    // 题主头像
    [self.header sd_setImageWithURL:GetUrlWithStr(model.MasterUserPictureName)];
    
    // 是否点赞
    if ([model.IsDoLike isEqualToString:@"1"]) {
        self.favoriteBtn.selected = YES;
    } else {
        self.favoriteBtn.selected = NO;
    }
    
    // 点赞数
    self.favorite.text = model.LikeCount.length ? model.LikeCount : @"0";
    
    // 评论数
    self.comment.text = model.CommentCount.length ? model.CommentCount : @"0";;
    
    // 转发数
    self.forward.text = model.ShareCount.length ? model.ShareCount : @"0";;
    
    // 回答者头像
    [self.rotatingImg sd_setImageWithURL:GetUrlWithStr(model.UserPictureName)];
    
    // 回答者姓名
    self.owner.text = model.NickName;
    
    // 回答者性别
    if ([model.Sex isEqualToString:@"1"]) {
        self.seximg.image = GetImgWithStr(@"男");
    } else {
        self.seximg.image = GetImgWithStr(@"女");
    }
    
    // 回答者年龄
    self.year.text = model.UserGroup;
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}


@end
